<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\LoginPost;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function index()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $status = Auth::attempt([
            'mobile' => $request->username,
            'password' => $request->password,
        ]);
        if (Auth::user()->status == 0) {
            if (Auth::check()) {
                Auth::logout();
                $request->session()->flush();
                $request->session()->regenerate();
            }
            return redirect('/login')->with('error', '账户已被锁定,请联系管理员');

        } elseif (Auth::user()->status == -1) {
            if (Auth::check()) {
                Auth::logout();
                $request->session()->flush();
                $request->session()->regenerate();
            }
            return redirect('/login')->with('error', '账户不存在,请联系管理员');
        }
        if ($status) {
            return redirect('/');
        }
        return redirect('/login')->with('error', '用户名或密码错误');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout(Request $request)
    {

        if (Auth::check()) {
            Auth::logout();
            $request->session()->flush();
            $request->session()->regenerate();
        }
        return redirect("/login");
    }
}
